import { defineStore } from 'pinia'
import { getRechargeList, getRechargeDetail, createRecharge, updateRecharge, deleteRecharge } from '@/api/recharge'

export const useRechargeStore = defineStore('recharge', {
  state: () => ({
    rechargeList: [],
    rechargeDetail: {},
    loading: false,
    total: 0
  }),

  actions: {
    // 获取充值记录列表
    async fetchRechargeList(params) {
      this.loading = true
      try {
        const response = await getRechargeList(params)
        this.rechargeList = response.data
        this.total = response.total
        return response
      } catch (error) {
        console.error('获取充值记录列表失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取充值记录详情
    async fetchRechargeDetail(id) {
      this.loading = true
      try {
        const response = await getRechargeDetail(id)
        this.rechargeDetail = response.data
        return response
      } catch (error) {
        console.error('获取充值记录详情失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 创建充值记录
    async createRecharge(data) {
      try {
        const response = await createRecharge(data)
        // 如果当前在充值记录列表页，重新获取列表
        if (this.rechargeList.length > 0) {
          await this.fetchRechargeList({})
        }
        return response
      } catch (error) {
        console.error('创建充值记录失败:', error)
        throw error
      }
    },

    // 更新充值记录
    async updateRecharge(id, data) {
      try {
        const response = await updateRecharge(id, data)
        // 更新充值记录列表中的数据
        const index = this.rechargeList.findIndex(recharge => recharge.id === id)
        if (index !== -1) {
          this.rechargeList[index] = { ...this.rechargeList[index], ...data }
        }
        // 如果是当前详情页的充值记录，也更新详情数据
        if (this.rechargeDetail.id === id) {
          this.rechargeDetail = { ...this.rechargeDetail, ...data }
        }
        return response
      } catch (error) {
        console.error('更新充值记录失败:', error)
        throw error
      }
    },

    // 删除充值记录
    async deleteRecharge(id) {
      try {
        const response = await deleteRecharge(id)
        // 从充值记录列表中移除
        this.rechargeList = this.rechargeList.filter(recharge => recharge.id !== id)
        this.total--
        return response
      } catch (error) {
        console.error('删除充值记录失败:', error)
        throw error
      }
    }
  }
})